package com.zn.controller;

import com.zn.common.constants.Constants;
import com.zn.common.resp.ApiResult;
import com.zn.common.utils.MD5Util;
import com.zn.common.utils.QrCodeUtils;
import com.zn.dto.*;
import com.zn.dto.UserDTO3;
import com.zn.pojo.UserInfo;
import com.zn.pojo.VeiReportInfo;
import com.zn.pojo.VeiReportInfo2;
import com.zn.services.UserService;
import com.zn.services.VeiReportInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author xyl
 * @create 2020/7/2 15:26
 * @desc 管理员接口 , 部分权限不够的需要设置拦截权限.后期会换成shiro
 **/
@Api(tags = "管理员操作接口")
@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private VeiReportInfoService veiReportInfoService;

    @ApiOperation("查看所有用户")
    @GetMapping("get-all-user")
    public ApiResult getAllUser(@RequestParam("uid") Integer uid) {
        return new ApiResult();
    }

    @ApiOperation("将用户状态改为失效")
    @PostMapping("delete-user")
    public ApiResult deleteUser(@RequestParam("uid") Integer uid) {
        return new ApiResult();
    }

    @ApiOperation("恢复用户状态")
    @PostMapping("renew-user")
    public ApiResult renewUser(@RequestParam("uid") Integer uid) {
        return new ApiResult();
    }

    @ApiOperation("添加普通用户")
    @PostMapping("add-user")
    public ApiResult addUser(@RequestBody UserDTO3 user) {
        UserInfo temp = userService.findUserByUN(user.getUsername());
        if (!ObjectUtils.isEmpty(temp)) {
            return new ApiResult(500, "此用户名已存在!");
        }
        userService.insertUserInfo(user);
        return new ApiResult();
    }

    @ApiOperation("升级权限用户")
    @PostMapping("promotion-user")
    public ApiResult promotionUser(@RequestBody UserDTO userDTO) {
        return new ApiResult();
    }

    @PostMapping("modify-report2")
    public ApiResult modifyReport2(@RequestBody VeiReportInfo2 info) {
        ApiResult result = new ApiResult();
        int count = veiReportInfoService.modifyReportInfo2(info);
        return result;
    }

    @GetMapping("get-user-all")
    public ApiResult<List<UserInfo>> getUserAll() {
        ApiResult result = new ApiResult();
        List<UserDTO3> list = userService.getAll();
        result.setData(list);
        return result;
    }

    @GetMapping("view-all")
    public ApiResult viewVeiReport(@RequestParam(value = "rid", required = false) Integer rid,
                                   @RequestParam(value = "status", required = false) Integer status) {
        ApiResult result = new ApiResult();
        if (rid != null) {
            VeiReportInfo veiReportInfo = veiReportInfoService.getVeiReportInfoByRid(rid);
            result.setData(veiReportInfo);
        } else if (status != null) {
            List<VeiReportInfoDTO> info = veiReportInfoService.getAllUserReportByStatus(status);
            result.setData(info);
        }
        return result;
    }

    @GetMapping("view-all2")
    public ApiResult viewVeiReport2(@RequestParam(value = "rid", required = false) Integer rid,
                                    @RequestParam(value = "status", required = false) Integer status) {
        ApiResult result = new ApiResult();
        if (rid != null) {
            VeiReportInfo2 veiReportInfo = veiReportInfoService.getVeiReportInfo2ByRid(rid);
            result.setData(veiReportInfo);
        } else if (status != null) {
            List<VeiReportInfoDTO2> info = veiReportInfoService.getAllUserReport2ByStatus(status);
            result.setData(info);
        }
        return result;
    }

    @GetMapping("view-holder")
    public ApiResult viewHolderReport(@RequestParam Integer hid, @RequestParam Integer status) {
        ApiResult result = new ApiResult();
        List<VeiReportInfoDTO> info = veiReportInfoService.getReportByHid(status, hid);
        result.setData(info);
        return result;
    }

    @GetMapping("view-holder2")
    public ApiResult viewHolderReport2(@RequestParam Integer hid, @RequestParam Integer status) {
        ApiResult result = new ApiResult();
        List<VeiReportInfoDTO2> info = veiReportInfoService.getReport2ByHid(status, hid);
        result.setData(info);
        return result;
    }

    /**
     * 审核报告1
     *
     * @param info
     * @param request
     * @return
     */
    @PostMapping("verify")
    public ApiResult verifyReport(@RequestBody @Validated CheckReportDTO info, HttpServletRequest request) {
        info.setAdminId(request.getIntHeader("uid"));
        boolean con = veiReportInfoService.verifyReport(info);
        if (con) {
            return new ApiResult(200, "请求成功!");
        }
        return new ApiResult(500, "服务器错误...");
    }

    /**
     * 审核报告2
     *
     * @param info
     * @param request
     * @return
     */
    @PostMapping("verify2")
    public ApiResult verifyReport2(@RequestBody @Validated CheckReportDTO info, HttpServletRequest request) {
        info.setAdminId(request.getIntHeader("uid"));
        boolean con = veiReportInfoService.verifyReport2(info);
        if (con) {
            return new ApiResult(200, "请求成功!");
        }
        return new ApiResult(500, "服务器错误...");
    }

    /**
     * 签发报告1
     *
     * @param info
     * @param request
     * @return
     */
    @PostMapping("audit")
    public ApiResult auditReport(@RequestBody @Validated CheckReportDTO info, HttpServletRequest request) {
        info.setAdminId(request.getIntHeader("uid"));
        boolean con = veiReportInfoService.auditReport(info);
        VeiReportInfo reportInfo = veiReportInfoService.getVeiReportInfoByRid(info.getReportId());
        String qrCodeUrl = Constants.QRCODE_REPORT_URL1 + reportInfo.getReportId() + "&" + "token=" + reportInfo.getReportNumber().substring(6);
        try {
            QrCodeUtils.encode(qrCodeUrl, "", Constants.QRCODE_IMG_LOCAL_URL1, reportInfo.getReportNumber() + ".png", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (con) {
            return new ApiResult(200, "请求成功!");
        }
        return new ApiResult(500, "服务器错误...");
    }

    /**
     * 签发报告2
     *
     * @param info
     * @param request
     * @return
     */
    @PostMapping("audit2")
    public ApiResult auditReport2(@RequestBody @Validated CheckReportDTO info, HttpServletRequest request) {
        info.setAdminId(request.getIntHeader("uid"));
        boolean con = veiReportInfoService.auditReport2(info);
        VeiReportInfo2 reportInfo2 = veiReportInfoService.getVeiReportInfo2ByRid(info.getReportId());
        String qrCodeUrl = Constants.QRCODE_REPORT_URL2 + reportInfo2.getReport2Id() + "&" + "token=" + reportInfo2.getReportNumber().substring(6);
        try {
            QrCodeUtils.encode(qrCodeUrl, "", Constants.QRCODE_IMG_LOCAL_URL2, reportInfo2.getReportNumber() + ".png", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (con) {
            return new ApiResult(200, "请求成功!");
        }
        return new ApiResult(500, "服务器错误...");
    }

    @GetMapping("export_report_excel")
    public void exportReportExcel(@RequestParam("rid") Integer rid, HttpServletResponse response) {
        VeiReportInfo reportInfo = veiReportInfoService.getUserReportByRid(rid);
            XSSFWorkbook wb = veiReportInfoService.exportReportExcel(reportInfo);
            veiReportInfoService.addReport1PrintCount(rid);
            veiReportInfoService.modifyPrintTime(rid);
        try {
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reportInfo.getReportNumber() + ".xlsx", "utf-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("export_report2_excel")
    public void exportReportExcel2(@RequestParam("rid") Integer rid, HttpServletResponse response) {
        VeiReportInfo2 info2 = veiReportInfoService.getUserReport2ByRid(rid);
        XSSFWorkbook wb;
        try {
            if (info2.getReportNumber().contains("ZNHEBA")) {
                /**
                 * 导出唐山报告2 模板
                 */
                wb = veiReportInfoService.exportTsReport2Excel(info2);
            } else {
                wb = veiReportInfoService.exportReport2Excel(info2);
            }
            veiReportInfoService.addReport2PrintCount(rid);
            veiReportInfoService.modifyPrintTime2(rid);
            //浏览器响应下载
            response.setContentType("application/vnd.ms-excel");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(info2.getReportNumber() + ".xlsx", "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            OutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                wb.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
